// pages/order/orderDetails/orderDetails.js
var ajax = require('../../../utils/httpUtil.js');
var dateCalu = require('../../../utils/dateUtils.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        payTime: '',
        interval: '',
		isClick:1, //1可点击 0不可以点击
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        console.log("~~~~~~onLoad~~~~~~~~~~~~~");
        var that = this;
        var id = options.id;
        loadData(that, id);
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onShow: function(options) {
        // console.log("~~~~~~onShow~~~~~~~~~~~~~");
        // var that = this;
        // var id = options.id;
        // loadData(that, id);
    },

    /**
     * 评价
     */
    evaluateOrder: function(e) {
        var orderId = e.currentTarget.dataset.id;
        var shopTitle = e.currentTarget.dataset.shoptitle;
        wx.navigateTo({
            url: '../../order/evaluate/evaluate?orderId=' + orderId + "&shopTitle=" + shopTitle + "&typeUrl=" + 2
        })
    },

    /**
     * 删除订单
     */
    deleteOrder: function(e) {
        var that = this;
        var orderId = e.currentTarget.dataset.id;
        updateOrdersInfo(6, orderId, that, 1);
    },

    /**
     * 取消订单
     */
    cancelOrder: function(e) {
        var that = this;
        var orderId = e.currentTarget.dataset.id;
        updateOrdersInfo(5, orderId, that, 1);
    },

    /**
     * 联系商家
     */
    linkShop: function(e) {
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone, //此号码并非真实电话号码，仅用于测试
            success: function() {
                console.log("拨打电话成功！")
            },
            fail: function() {
                console.log("拨打电话失败！")
            }
        });
    },

    /**
     * 去支付
     */
    payOrder: function(e) {
        var orderId = e.currentTarget.dataset.id;
        console.log(orderId);

        ajax.reqPost('/xorder/payOrdersInfo', {
            id: orderId
        }, function(res) {
            console.log(res);
            wx.requestPayment({
                'timeStamp': res.returnObject.timestamp + '',
                'nonceStr': res.returnObject.noncestr + '',
                'package': res.returnObject.wxpackage + '',
                'signType': 'MD5',
                'paySign': res.returnObject.paySign + '',
                'success': function(res) {
                    console.log(res)
                },
                'fail': function(res) {
                    console.log(res);
                    if (res === 'requestPayment:fail cancel') {
                        console.log('用户取消支付,返回订单列表并刷新');
                    }
                },
                'complete': function(res) {
                    console.log(res)
                }
            })    
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },

    /**
     * 监听页面关闭
     */
    onHide: function() {
        var that = this;
        //停止定时器
        clearInterval(that.data.interval);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        //控制点击左上角返回
        var that = this;
        //停止定时器
        clearInterval(that.data.interval);
    },

})

/**
 * 修改订单状态
 * status 5=取消订单 6=删除订单
 * id 订单id
 */
function updateOrdersInfo(status, id, that, isTips) {
	if (that.data.isClick == 1) {
		that.setData({
			isClick: 0,
		})
	} else {
		return;
	}
    console.log("进入取消订单~~~~~~~~~~~~~~~~~~~");
    ajax.reqPost('xorder/updateOrdersInfo', {
        id: id,
        status: status
    }, function(res) {
        console.log(res);
        if (res.resultCode == 1000) {

            if (isTips == 1) { //需要提示
                wx.showToast({
                    title: status == 5 ? "取消成功" : "删除成功",
                    icon: 'success',
                    mask: true,
                    duration: 2000
                })
            }
			that.setData({
				isClick: 1
			})
            if (status == 5) { //取消订单刷新当前页面
                console.log("取消订单刷新当前页面");
                //刷新页面
                loadData(that, id);
            } else { //删除订单跳转到订单列表页面
                console.log("删除订单跳转到订单列表页面");
                wx.reLaunch({
                    url: '../../order/orderList/orderList'
                })
            }
		} else if (res.resultCode == 1010) {
			that.setData({
				isClick: 1
			})
			wx.showToast({
				title: res.returnObject,
				icon: 'none',
				duration: 1000
			})
		}
		
    });
}

/**
 * 倒计时 
 */
function countDown(createTime, that, id) {

    that.data.interval = setInterval(function() {
        //根据创建时间和当前时间计算时间差爱
        var dateMap = dateCalu.getTwoTime(createTime, dateCalu.formatDate(new Date()));
        console.log(dateMap);

        //时间差大于15分钟直接取消订单，小于15分钟页面展示倒计时时间
        if (dateMap.m >= 15 || dateMap.h > 0 || dateMap.d > 0) {
            console.log("大于15分钟取消订单~~~~~");
            //停止定时器
            clearInterval(that.data.interval);
            //取消订单
            updateOrdersInfo(5, id, that, 0);
        } else {
            //页面展示倒计时
            console.log("页面展示倒计时~~~~~");
            var countDownTime1 = 14 - dateMap.m;
            var countDownTime2 = 60 - dateMap.s;

            var countDownTime = countDownTime1 + ":" + countDownTime2;
            console.log("倒计时时间=", countDownTime);
            var time = countDownTime.split(":");
            var minute = parseInt(time[0]);
            var second = parseInt(time[1]);

            if (minute == 0 && second == 0) { //倒计时结束，结束定时器
                //停止定时器
                clearInterval(that.data.interval);
                //取消订单
                console.log("页面倒计时到时，取消订单~~~~~");
                updateOrdersInfo(5, id, that, 0);
            } else {
                if (second > 0) {
                    second--;
                } else if (second == 0) {
                    minute--;
                    second = 59;
                }

                var payTimeSecond = (second < 10) ? '0' + second : second;
                var payTimeMinute = (minute < 10) ? '0' + minute : minute;
                console.log("倒计时页面展示的时间=" + payTimeMinute + ":" + payTimeSecond);
                that.setData({
                    payTime: payTimeMinute + ":" + payTimeSecond
                })
            }
        }
    }, 1000)
}

/**
 * 加载数据
 */
function loadData(that, id) {
    ajax.reqPost('xorder/getOrdersById', {
        id: id
    }, function(res) {
        console.log(res);
        if (res.resultCode == 1000) {
            var order = res.returnObject.list[0]; //订单详情

            if (order != null) {
                var goodsList = order.list; //食品列表
                var activityIds = order.activityIds; //参与的活动
                console.log(activityIds);
                for (var i = 0; i < goodsList.length; i++) {
                    goodsList[i].goodsPrice = (goodsList[i].goodsPrice * goodsList[i].goodsNum).toFixed(0);
                }

                var activityList = [];
                var activityMoneyCount = 0;
                if (activityIds) {
                    activityIds = activityIds.split(",");
                    console.log(activityIds.length);
                    for (var i = 0; i < activityIds.length; i++) {
                        var activity = new Object;
                        activity.title = activityIds[i].split("-")[0];
                        activity.money = activityIds[i].split("-")[1];
                        activityList.push(activity);
                        activityMoneyCount += Number(activity.money);
                    }
                }
                console.log(activityList);
                that.setData({
                    order,
                    goodsList,
                    activityList,
                    activityMoneyCount,
                    payTime: ''
                })

                if (order.status == 1) { //待支付
                    console.log("进入倒计时order.status=" + order.status + "创建时间=" + order.createTime);
                    //倒计时
                    countDown(order.createTime, that, order.id);
                }

            }
        }
    });
}